package com.acg.auth.config;

import com.acg.auth.pojo.SysLoginLog;
import com.acg.auth.service.SysLoginLogService;
import com.acg.security.custom.CustomUser;
import com.acg.util.IPUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;

import org.springframework.security.authentication.event.AuthenticationSuccessEvent;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;

/**
 * @Description TODO
 * @Author 没有脑袋
 * @Date 2025/8/4 9:33
 */
@Component
@Slf4j     // 日志输出注解
public class MySuccessListence implements ApplicationListener<AuthenticationSuccessEvent> {

    /**
     * 日志服务类
     */
    @Autowired
    private SysLoginLogService service;

    /**
     * 用户登录成功进行调用
     * @param event the event to respond to
     */

    @Override
    public void onApplicationEvent(AuthenticationSuccessEvent event) {
        // 1、 创建登录日志
        SysLoginLog loginLog = new SysLoginLog();

        loginLog.setStatus(true);  // 登录成功
        loginLog.setCreateTime(LocalDateTime.now());  // 创建时间
        loginLog.setAccessTime(LocalDateTime.now()); // 访问时间
        loginLog.setMsg("登录成功");
        loginLog.setUpdateTime(LocalDateTime.now());

        // ip  获取request对象

        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        String ipAddr = IPUtils.getIpAddr(request);
//        request.getRequestURI() // 获取路径
        loginLog.setIpaddr(ipAddr);

        /**
         * 获取此时登录的名字
         */
        CustomUser customUser = (CustomUser) event.getAuthentication().getPrincipal();



        System.err.println("当前用户名："+customUser.getSysUser().getUsername());
         // 此时登录的用户名
        loginLog.setUsername(customUser.getSysUser().getUsername());

        // 获取当前密码信息
        System.err.println("密码"+customUser.getSysUser().getPassword());



        // 增加日志
        boolean save = service.save(loginLog);

        System.out.println("日志新增："+save + "数据："+loginLog);

    }
}
